package impl;

import anaydis.sort.SorterType;

import java.util.Comparator;
import java.util.List;

public class QuickSorter extends AbstractSorter {
    public QuickSorter() {
        super(SorterType.QUICK);
    }

    public <T> void sort(Comparator<T> comparator, List<T> list) {

        littleSort(comparator, list, 0, list.size() - 1);
    }

    private <T> void littleSort(Comparator<T> comparator, List<T> list, int inicio, int fin) {

        if (inicio >= fin) return;

        int xi = inicio - 1;
        int xj = fin;

        while (true) {

            while (greater(comparator, list, fin, ++xi)) {
                if (xi == fin) {
                    break;
                }
            }
            while (greater(comparator, list, --xj, fin)) {
                if (xj <= inicio) {
                    break;
                }
            }
            if ((xj <= xi)) {
                swap(list, xi, fin);
                break;
            } else {
                swap(list, xi, xj);
            }

        }
        littleSort(comparator, list, inicio, xi - 1);
        littleSort(comparator, list, xi + 1, fin);

    }
}

